﻿using D.Traceability.Domain;
using D.Traceability.ErrorCode;
using D.Traceability.Infrastructure.Infrastructure;
using D.Traceability.Write.API.APPlicant.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.Traceability.Write.API.APPlicant.CommandHandler
{
    /// <summary>
    ///  批量删除溯源数据(逻辑删)
    /// </summary>
    public class DeleteTraceCommandHandler : IRequestHandler<DeleteTraceCommand, APIResult<string>>
    {
        private readonly IBaseRepository<SU_TraceabilityModel> baseRepository;

        public DeleteTraceCommandHandler(IBaseRepository<SU_TraceabilityModel> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        /// <summary>
        ///  批量删除溯源数据(逻辑删)
        /// </summary>
        public async Task<APIResult<string>> Handle(DeleteTraceCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();

            //第二个方法
            var batchArr = request.TraceaBatch.ToArray();

            var listArray = await baseRepository.GetAll().Result.Where(x=> batchArr.Contains(x.TraceaBatch)).ToListAsync();

            foreach ( var batch in listArray)
            {
                batch.TraceaIsDelete = true;
            }

            var res =  baseRepository.UpdateRanhes(listArray).Result;
            result.Msg = "成功批量删除" + res + "条";
            result.Code = APIEnum.删除成功;


            ////第一个方法
            //var list = await baseRepository.GetAll().Result.Where(x => request.TraceaBatch.Contains(x.TraceaBatch)).ToListAsync();
            ////记录条数
            //int num = 0;
            //foreach (var item in list)
            //{
            //    //逻辑删除
            //    item.TraceaIsDelete = true;
            //    await baseRepository.Update(item);
            //    num++;
            //}
            //if (num == 0)
            //{
            //    result.Code = APIEnum.删除失败;
            //    result.Msg = APIEnum.删除失败.ToString();
            //}
            //else
            //{
            //    result.Msg = "成功删除" + num + "条";
            //    result.Code = APIEnum.删除成功;
            //}
        
            return await Task.FromResult(result);
        }
    }
}
